package com.bodystm.server;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;
import javax.print.DocFlavor.URL;
import javax.servlet.ServletConfig;

import org.apache.commons.codec.language.bm.Languages.LanguageSet;
import org.apache.commons.lang.ArrayUtils;
import org.hibernate.type.TrueFalseType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bodystm.bean.Bed;
import com.bodystm.bean.BloodPressure;
import com.bodystm.bean.BloodPressureDevice;
import com.bodystm.bean.HistoricalData;
import com.bodystm.bean.Oximetry;
import com.bodystm.bean.OximetryDevice;
import com.bodystm.bean.Patient;
import com.bodystm.bean.PatientBedUser;
import com.bodystm.bean.Temperature;
import com.bodystm.config.PublicSetting;
import com.bodystm.dao.BedDao;
import com.bodystm.service.BedService;
import com.bodystm.service.BloodPressureService;
import com.bodystm.service.HistoricalDataService;
import com.bodystm.service.OximetryService;
import com.bodystm.service.PatientBedService;
import com.bodystm.service.PatientService;
import com.bodystm.service.TemperatureService;
import com.bodystm.system.SystemSetting;
import com.bodystm.util.SerializeUtil;
import com.bodystm.web.ConcentratorDevice;
import com.bodystm.web.DeviceSettings;
import com.bodystm.web.Filter4DataGather;
import com.bodystm.web.GatherServerStatic;
import com.bodystm.web.TemperatureDevice;

import redis.clients.jedis.Jedis;


/**
 * 鏁版嵁鑾峰彇瀵硅薄
 * 
 * @author ggeagle
 *
 */
public class DataGather implements Runnable {
	/**
	 * 日志记录器
	 */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 消息最小长度
	 */
	static final int MIN_LENGTH = 12;
	/**
	 * 消息边界
	 */
	static final int MSG_SEP = 0X7E;
	/**
	 * 消息边界
	 */
	static final int MSG_SEP_END = 0XAA;
	/**
	 * Socket连接对象
	 */
	private Socket socket;
	private ServletConfig servletConfig;
	/**
	 * JDBC信息操作对象
	 */
	private TemperatureService temperatureService;
	private PatientService patientService;
	private PatientBedService patientBedUserService;
	private BedService bedService;
//	private HistoricalDataService historicalDataService;
	
	
	private String mac="";
	private byte[] macBytes=null;
	TemperatureDevice temperatureDevice=null;

	BloodPressureDevice bloodPressureDevice=null;

	HistoricalData historData = new HistoricalData();
	
	OximetryDevice oximetryDevice=null;

	private BloodPressureService bloodPressureService;

	private OximetryService oximetryService;
	
	ScheduleMQ4Ecg scheduleMQ4Ecg=null;
	ScheduleMQ4Oximetry scheduleMQ4Oximetry=null;
	ScheduleMQ4PBP scheduleMQ4PBP=null;
	ScheduleMQ4RESP scheduleMQ4RESP=null;
	
	public DataGather(Socket socket,ServletConfig servletConfig, TemperatureService temperatureService,PatientService patientService,PatientBedService patientBedUserService,BedService bedService) {
		this.socket = socket;
		this.servletConfig=servletConfig;
		this.temperatureService = temperatureService;
		this.patientService=patientService;
		this.patientBedUserService=patientBedUserService;
		this.bedService=bedService;
		WebApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(servletConfig.getServletContext());
		bloodPressureService=(BloodPressureService)context.getBean("bloodPressureService");
		oximetryService=(OximetryService)context.getBean("oximetryService");
	}

	/**
	 * 发送响应信息
	 */
	private void sendResponse(DataResponse dataResponse) {
		byte[] result = null;
		BufferedOutputStream pw = null;
		try {
			pw = getWriter(socket);
			result = new byte[dataResponse.getLength() + 3];
			int index = 0;
			result[index++] = 0X7E;
			result[index++] = dataResponse.getMsgId();
			result[index++] = 0X00;
			for (byte b : dataResponse.getEquipNo()) {
				result[index++] = b;
			}
			result[index++] = dataResponse.getSerialNo();
			result[index++] = dataResponse.getCheckSum();
			result[index] = 0X7E;//(byte) 0XAA;
			//logger.info("响应消息为：{}", ByteUtil.convertByteToString(result));
			//logger.info("响应消息的十进制为：{}", result);
			pw.write(result);
			pw.flush();
		} catch (IOException e) {
			logger.error("不能向客户端发送响应信息：{}",
					ByteUtil.convertByteToString(result), e);
		}
	}

	/**
	 * 对消息进行转义
	 * 
	 * @param dataBytes
	 *            消息字节数组
	 * @return
	 */
	private byte[] unescape(byte[] dataBytes) {
		byte[] destArrays = null;
		int index = 0;
		if (dataBytes != null && dataBytes.length > 2) {
			destArrays = new byte[dataBytes.length];
			destArrays[index++] = MSG_SEP;
			for (int i = 1; i < dataBytes.length - 1; i++) {
				if (dataBytes[i] == 0X7D && dataBytes[i + 1] == 0X01) {
					destArrays[index++] = 0X7D;
					i = i + 1;
				} else {
					destArrays[index++] = dataBytes[i];
				}
			}
			destArrays[index++] = MSG_SEP;//(byte) MSG_SEP_END;
			int totalNum = index;
			index = 1;
			for (int i = 1; i < totalNum - 1; i++) {
				if (destArrays[i] == 0X7D && destArrays[i + 1] == 0X02) {
					dataBytes[index++] = 0X7E;
					i = i + 1;
				} else {
					dataBytes[index++] = destArrays[i];
				}
			}
			dataBytes[index++] = MSG_SEP;//(byte) MSG_SEP_END;
		}
		if (index > 0) {
			destArrays = ArrayUtils.subarray(dataBytes, 0, index);
		} else {
			destArrays = new byte[0];
		}
		return destArrays;
	}

	SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");
	Calendar dateOne=Calendar.getInstance(),dateTwo=Calendar.getInstance();
	PatientBedUser patientBedUser;
	/**
	 * 执行数据的校验与解析
	 * 
	 * @param dataBytes
	 *            字节信息
	 * @return
	 * @throws ParseException 
	 */
	private Temperature checkDataInfo(byte[] dataBytes, DataResponse response) {
		Temperature temperature = null;
		boolean flag = true;
		boolean ifexp=false;
		if (dataBytes.length !=25) {
			logger.info("接收到的信息:{}",ByteUtil.convertByteToString(dataBytes));
			logger.error("消息长度不对，应为25个字节");
			flag = false;
		} else if ((dataBytes[0] != MSG_SEP&&dataBytes[0]!=-86)
				|| (dataBytes[dataBytes.length - 1] != MSG_SEP&&dataBytes[dataBytes.length - 1] !=-1)) {
			logger.error("消息的起动地址或结束符号不对");
			flag = false;
		} 
		if (flag) {
			if(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 0, 2)).equals("AA55")){
				String mac4Concentrator=ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 2, 8));
				ConcentratorDevice concentratorDevice=null;
				if(DeviceSettings.lstMacs4Concentrator.contains(mac4Concentrator)){
					concentratorDevice=(ConcentratorDevice)DeviceSettings.hasDevice4Concentrator.get(mac4Concentrator);
					concentratorDevice.setLastMsgTime(new Date());
					concentratorDevice.setSignaled(true);
					if(!concentratorDevice.isWarningOrNot())concentratorDevice.setWarningOrNot(true);
				}/*else{
					DeviceSettings.lstMacs4Concentrator.add(mac4Concentrator);
					concentratorDevice=new ConcentratorDevice();
					concentratorDevice.setConcentratorNo(mac4Concentrator);
					DeviceSettings.hasDevice4Concentrator.put(mac4Concentrator, concentratorDevice);
				}
				concentratorDevice.setLastMsgTime(new Date());*/
				return null;
			}
			temperature = new Temperature();

			response.setMsgId(dataBytes[1]);
			//**************************************设备管理页面过滤按钮，点击后开始数据过滤，只收取软件发过来的数据
			String strMaczhuji=ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 10, 16));
			String strMacdevice="";//温度贴片mac地址
			//mac 地址
			String mscAddress=ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 3, 9));
			strMacdevice=mscAddress;
			String strConcentratorMac=ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 10, 16));
			temperature.setConcentratorNo(strConcentratorMac);
			//忽略还没有添加病人的贴片上传的数据
			if (!DeviceSettings.ifgotMacs4CurrentPatients) {
				DeviceSettings.ifgotMacs4CurrentPatients=true;
				for (PatientBedUser pbu : patientBedUserService.getCurrentPatients()) {
					DeviceSettings.lstMacs4CurrentPatients.add(pbu.getPatient().getEquipNo());
				}
			}
			if (!DeviceSettings.lstMacs4CurrentPatients.contains(strMacdevice)) {
				logger.error("该设备当前没有对应的病人");
				if (!DeviceSettings.lstMacs4NoPatients.contains(strMacdevice)) {
					DeviceSettings.lstMacs4NoPatients.add(strMacdevice);
				}
				ifexp=true;
				//未识别设备相关
				DeviceSettings.hasMacTem4NoPatient.put(strMacdevice, Float.parseFloat(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 16, 17))+ "."+ ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 17, 18))));
				return null;
			}else if(DeviceSettings.lstMacs4NoPatients.contains(strMacdevice)){
				DeviceSettings.lstMacs4NoPatients.remove(strMacdevice);
				DeviceSettings.hasMacTem4NoPatient.remove(strMacdevice);
			}
			//判断全局变量中是否含有此设备，没有则新建，有则获取
			TemperatureDevice temperatureDevice=null;
			float olddegree=0;
			if(DeviceSettings.lstMacs.contains(strMacdevice)){
				temperatureDevice=(TemperatureDevice)DeviceSettings.hasDevice.get(strMacdevice);
			}else{
				DeviceSettings.lstMacs.add(strMacdevice);
				temperatureDevice=new TemperatureDevice();
				temperatureDevice.setStrMac(strMacdevice);
				DeviceSettings.hasDevice.put(strMacdevice, temperatureDevice);
			}
			//如果获取不到第一次存储时间则将当前时间作为第一次的时间,获取到了则与现在的时间作比较，间隔超过50小时则直接忽略
			if(temperatureDevice.getFirstSavTime()==null){
				temperatureDevice.setFirstSavTime(new Date());
			}else{
				if(((new Date()).getTime()-temperatureDevice.getFirstSavTime().getTime())/3600000>=SystemSetting.NUM4EXPIREHOURS){
					if(temperatureDevice.getWarningOrNot4NoPower()==null){
						temperatureDevice.setWarningOrNot4NoPower(true);
					}
					return null;
				}
					
			}
			//**************************************
			response.setEquipNo(ArrayUtils.subarray(dataBytes, 3, 9));
			response.setSerialNo(dataBytes[9]);
			if (dataBytes.length > MIN_LENGTH) {			
				// 获取温度2信息
				String value = ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 18, 19))+ "."+ ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 19, 20));
				try {
					temperature.setMeasureNum(Float.parseFloat(value));//Two
				} catch (NumberFormatException e) {
					e.printStackTrace();
					return null;
				}
				float envTemp=Float.parseFloat(value);
				// 获取温度1信息
				value = ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 16, 17))+ "."+ ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 17, 18));
				try {
					temperature.setMeasureNum(Float.parseFloat(value));//Three
				} catch (NumberFormatException e) {
					e.printStackTrace();
					return null;
				}
				float degree=0;//从数据获取的温度数据
				boolean ifdegreeEQ0=false;//用于当温差过大，大于0.6则显示上一个正常值
				Date curTime=new Date();
				if(temperatureDevice!=null){				
					try {
						degree=CalibrateRealTemp(Float.parseFloat(value),envTemp,true);
						//做20分钟内的平均数
						//if(temperatureDevice.getDate4DataIn20Min()==null)temperatureDevice.setDate4DataIn20Min(new ArrayList<Date>());
						//if(temperatureDevice.getDataIn20Min()==null)temperatureDevice.setDataIn20Min(new ArrayList<Float>());
						
						//处理偶然的异常，异常数据持续十分钟以上才显示，否则一直显示上一个正常值
						if((ByteUtil.convertByteToString(dataBytes[21])+ByteUtil.convertByteToString(dataBytes[20])).equals("0000")){
							//平均数机制，暂时注释掉，防止体温上升慢
							if((SystemSetting.ifGetAvgInDataGather4Temp==null?true:SystemSetting.ifGetAvgInDataGather4Temp)&&temperatureDevice.getFirstDataTime4Reach33()!=null&&(curTime.getTime()-temperatureDevice.getFirstDataTime4Reach33().getTime())/1000>=720){
								//logger.info("取平均值");
								List<Float> dataIn2Min=temperatureDevice.getDataIn2Min();
								List<Date> date4DataIn2Min=temperatureDevice.getDate4DataIn2Min();
								Date dateTemp=curTime;//new Date();	
								for(int i=0;i<date4DataIn2Min.size();i++){
									if((dateTemp.getTime()-date4DataIn2Min.get(i).getTime())/60000>2){
										date4DataIn2Min.remove(i);
										dataIn2Min.remove(i);
										i--;
									}else{
										break;
									}
								}
//								if(temperatureDevice.getUnusualDegree()>0){
								if(degree>0){
									date4DataIn2Min.add(dateTemp);
									dataIn2Min.add(degree);
									if(date4DataIn2Min.size()<=1){
										
									}else if(date4DataIn2Min.size()<=2){
										degree=(dataIn2Min.get(0)+dataIn2Min.get(1))/2;
									}else{
										float maxT=0;
										float minT=0;
										float totalT=0;
										for(int i=0;i<dataIn2Min.size();i++){
											if(i==0){
												maxT=dataIn2Min.get(i);
												minT=dataIn2Min.get(i);
											}else{
												maxT=dataIn2Min.get(i)>maxT?dataIn2Min.get(i):maxT;
												minT=dataIn2Min.get(i)<minT?dataIn2Min.get(i):minT;
											}
											totalT+=dataIn2Min.get(i);
										}
										degree=(totalT-minT-maxT)/(dataIn2Min.size()-2);
									}
								}
									
//								}
							}

						}else{
							if(degree<36.3){
								return null;
							}
						}
						
						degree+=temperatureDevice.getNum4Correct();
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						return null;
					}
					logger.info("mac:"+strMacdevice+"温度数据:"+(float)(Math.round((degree)*100))/100+"探头温度:"+Float.parseFloat(value)+"环境温度"+envTemp);
				}else{
					try {
						degree=CalibrateRealTemp(Float.parseFloat(value),envTemp,true);
						//degree=Float.parseFloat(value);
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						return null;
					}
				}
//				Date curTime=new Date();
				//**************************************利用算法预估稳定值*********************************************************
				
				try {
					Date firstDataTime=temperatureDevice.getFirstDataTime();
					if(firstDataTime==null){
						temperatureDevice.setFirstDataTime(curTime);
						firstDataTime=curTime;
						//logger.info(strMacdevice+"第一次接收到数据，时间为："+temperatureDevice.getFirstDataTime().toString());
					}
					
					if(temperatureDevice.getFirstDataTime4Reach33()==null||(curTime.getTime()-temperatureDevice.getFirstDataTime4Reach33().getTime())/1000<=720){
						float ttwd=Float.parseFloat(value);
						if(temperatureDevice.getFirstDataTime4Reach33()!=null){//||ttwd>35){//||temperatureDevice.isIfGatherData()
							//temperatureDevice.setIfGatherData(true);
							List<Float> dataIn5Min=temperatureDevice.getDataIn20Min();
							List<Date> date4DataIn5Min=temperatureDevice.getDate4DataIn20Min();
							dataIn5Min.add(ttwd);
							date4DataIn5Min.add(curTime);
						}else//如果之前还没有大于33的温度
						//if(temperatureDevice.getFirstDataTime4Reach33()==null)
						{
							if(ttwd>33){
								List<Float> dataIn5Min=temperatureDevice.getDataIn20Min();
								List<Date> date4DataIn5Min=temperatureDevice.getDate4DataIn20Min();
								dataIn5Min.add(ttwd);
								date4DataIn5Min.add(curTime);
								temperatureDevice.setFirstDataTime4Reach33(curTime);
								if(temperatureDevice.getDate4Last33()==null){//如果上数的第一个数就大于33，则将当前时间设置为Date4Last33
									temperatureDevice.setDate4Last33(curTime);
								}
								//temperatureDevice.setIndex4Last33(temperatureDevice.getDataIn20Min().size()-2);
							}else{
								temperatureDevice.setDate4Last33(curTime);
							}
						}
					}else{
						
						//temperatureDevice.setIfGatherData(false);
						/*if(!temperatureDevice.isIfEstimated()){//如果还没有预估过
							temperatureDevice.setEstimatedT(Estimate.getStableValue2(temperatureDevice.getDataIn20Min(), temperatureDevice.getDate4DataIn20Min()));
							logger.info(strMacdevice+"计算出稳定值："+temperatureDevice.getEstimatedT()+"共用时间："+((new Date()).getTime()-curTime.getTime())+"毫秒"+temperatureDevice.getDataIn20Min().size());
							temperatureDevice.setIfEstimated(true);
						}
						if((curTime.getTime()-firstDataTime.getTime())/60000<=15){
							degree=temperatureDevice.getEstimatedT();
							logger.info(strMacdevice+"用计算出的稳定值代替收取的真实值："+degree);
						}*/
					}
					
					if(temperatureDevice.getFirstDataTime4Reach33()!=null){
						if(!temperatureDevice.isIfEstimated()&&(curTime.getTime()-temperatureDevice.getDate4Last33().getTime())/1000>300){
							temperatureDevice.setIfEstimated(true);
							float ResultOfLP=Estimate.getStableValue3(temperatureDevice.getDataIn20Min(), temperatureDevice.getDate4DataIn20Min(),temperatureDevice.getDate4Last33());//temperatureDevice.getFirstDataTime4Reach33());
							//logger.info(strMacdevice+"老庞算法5分钟算出的平衡值为："+ResultOfLP+"输入参数个数为："+temperatureDevice.getDataIn20Min().size());
						}
						if(!temperatureDevice.isIfEstimatedOF3Min()&&(curTime.getTime()-temperatureDevice.getDate4Last33().getTime())/1000>180){
							temperatureDevice.setIfEstimatedOF3Min(true);
							float ResultOfLP=Estimate.getStableValue3(temperatureDevice.getDataIn20Min(), temperatureDevice.getDate4DataIn20Min(),temperatureDevice.getDate4Last33());//temperatureDevice.getFirstDataTime4Reach33());
							temperatureDevice.setEstimatedT4LP3(ResultOfLP);
							//logger.info(strMacdevice+"老庞算法3分钟算出的平衡值为："+ResultOfLP+"输入参数个数为："+temperatureDevice.getDataIn20Min().size());
						}
						
					}
					//一直用算法估值
					if(temperatureDevice.getFirstDataTime4Reach33()!=null){
						int secondsAfterReach33=(int) ((curTime.getTime()-temperatureDevice.getFirstDataTime4Reach33().getTime())/1000);
						if(secondsAfterReach33<180){
							degree=Float.parseFloat(value);//前三分钟不进算法
							degree+=(float)secondsAfterReach33/300+0.2;
							temperatureDevice.getResult4Latest3Times().add(degree);
							if(temperatureDevice.getResult4Latest3Times().size()>2){
								temperatureDevice.getResult4Latest3Times().remove(0);
							}
							//logger.info("secondsAfterReach33:"+secondsAfterReach33+"FirstDataTime4Reach33:"+temperatureDevice.getFirstDataTime4Reach33().getTime());
							//logger.info(strMacdevice+"用算法估值之前的补偿,补偿结果为："+degree+"补偿值为:"+((float)secondsAfterReach33/300+0.2));
						}else if(secondsAfterReach33>=180&&secondsAfterReach33<=720){
							temperatureDevice.setEstimatedT(Estimate.getStableValue4(temperatureDevice));
							//logger.info(strMacdevice+"计算出稳定值："+temperatureDevice.getEstimatedT()+"共用时间："+((new Date()).getTime()-curTime.getTime())+"毫秒"+temperatureDevice.getDataIn20Min().size());
							if(secondsAfterReach33<=300&&temperatureDevice.getEstimatedT4LP3()>0){
								degree=(float) (temperatureDevice.getEstimatedT4LP3()+Math.random()*0.2-0.1);
								//logger.info(strMacdevice+"用老庞三分钟计算出的稳定值代替收取的真实值："+degree);
							}else{
//								degree=temperatureDevice.getEstimatedT();
								if(temperatureDevice.getEstimatedT4LP3()>0&&secondsAfterReach33<=420){
									degree=(temperatureDevice.getEstimatedT()+temperatureDevice.getEstimatedT4LP3())/2;
									//logger.info(strMacdevice+"用老梁计算出的稳定值和庞算出的稳定值"+temperatureDevice.getEstimatedT()+"作平均代替收取的真实值："+degree);
								}else{//7-12分钟
									degree=temperatureDevice.getEstimatedT()+(float)Math.random()*0.2f-0.1f;
								}
//								logger.info(strMacdevice+"用老梁计算出的稳定值代替收取的真实值："+degree);
							}
							
						}else{//12分钟以后
							if(temperatureDevice.getDataIn20Min().size()>0){
								temperatureDevice.getDataIn20Min().clear();
								temperatureDevice.getDate4DataIn20Min().clear();
								temperatureDevice.getResult4Latest3Times().clear();
							}
							if(degree==0){//如果温差过大则采用上一次的正常值作为当前温度
								ifdegreeEQ0=true;
								degree=temperatureDevice.getLastDegree()+(float)Math.random()*0.2f-0.1f;
								//打开胳膊的情况，温差过大
								if(temperatureDevice.getOpenArmsTime()==null){
									temperatureDevice.setOpenArmsTime(curTime);
								}else if((curTime.getTime()-temperatureDevice.getOpenArmsTime().getTime())/60000>=30){//如果打开胳膊状态持续时间大于30分钟则开始显示当前采集的数据
									degree=CalibrateRealTemp(Float.parseFloat(value),envTemp,false);
									
									if (temperatureDevice.isIfReNormal4OpenArms()) {
										temperatureDevice.setWarningOrNot4OpenArms(true);
									}
									//temperatureDevice.setIfReNormal4OpenArms(false);
								}
							}else{//非异常情况
								if(temperatureDevice.getOpenArmsTime()!=null){
									temperatureDevice.setOpenArmsTime(null);
								}
								temperatureDevice.setIfReNormal4OpenArms(true);
							}
						}
						
					}
				} catch (NumberFormatException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				//***********************************************************************************************
//				temperature.setMeasureNumOne((float)(Math.round((degree)*100))/100);//20160801
				//将最新的当前温度数据赋值给静态变量，以便前台能方便的随时获取实时温度数据
				if(temperatureDevice!=null){
					if(ifdegreeEQ0){//如果当前算法得出结果为0
						
					}else{
						temperatureDevice.setLastDegree(degree);//如果此次温度结果为有效值则更新LastDegree（上一个有效值）
					}
					olddegree=temperatureDevice.getCurrentDegree();
					//如果是新替换的贴片，则忽略前十分钟的数据,用上个贴片的最后数据代替
					if (temperatureDevice.getDegree4LastMac()>0&&(temperatureDevice.getFirstDataTime4Reach33()==null||//temperatureDevice.getFirstDataTime4Reach33()!=null&&(
							(int) ((curTime.getTime()-temperatureDevice.getFirstDataTime4Reach33().getTime())/1000)<600)) {
						degree=temperatureDevice.getDegree4LastMac()+(float)Math.random()*0.2f-0.1f;
					}
					temperatureDevice.setCurrentDegree(degree);
				}
				temperature.setMeasureNum((float)(Math.round((degree)*100))/100);
				// 获取电量
				try {
					temperature.setPowerNum(Integer.parseInt(ByteUtil.convertByteToString(dataBytes[22])));
					temperatureDevice.setPowerNum(Integer.parseInt(ByteUtil.convertByteToString(dataBytes[22])));
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}
				//修改设备状态记录
				patientBedUser=DeviceSettings.hasDevice4PBUOfMacs.get(strMacdevice);
				if(patientBedUser==null){//如果内存中没有相应数据则从数据库中获取
					patientBedUser=patientBedUserService.getPatientBedUserByMac(strMacdevice);
					DeviceSettings.hasDevice4PBUOfMacs.put(strMacdevice, patientBedUser);
				}
				if(patientBedUser!=null){
					if(patientBedUser.getStatusOfDevice()==null||patientBedUser.getStatusOfDevice()==0){
						patientBedUser.setStatusOfDevice(1);
						patientBedUserService.saveEntity(patientBedUser);
					}
				}
				
				//判断是否五分钟内存储过了数据，如果没有则存储，并根据时差做两个温度的差值补上没有的数据
				Date lastSavTime;
//				Date curTime=new Date();
				dateTwo.setTime(curTime);
				//判断是否为历史数据,如果是历史数据则将计算出的历史时间作为curTime
				if(!(ByteUtil.convertByteToString(dataBytes[21])+ByteUtil.convertByteToString(dataBytes[20])).equals("0000")){
					try {
						dateTwo.setTime(temperatureDevice.getFirstSavTime());
						dateTwo.add(Calendar.MINUTE, Integer.parseInt(ByteUtil.convertByteToString(dataBytes[21])+ByteUtil.convertByteToString(dataBytes[20]),16));
						//如果添加病人以及某个贴片后，中间服务器重启了，会造成上边计算出的历史时间后于现在时间，此情况则忽略历史数据
						if(curTime.getTime()<=dateTwo.getTime().getTime())
							return null;
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						return null;
					}
					
				}
				lastSavTime=temperatureDevice.getLastSavTime();//最后数据上传时间
				if(lastSavTime!=null){//如果不为空则判断是否要存，为空则直接存储，不作其他处理
					//Calendar dateOne=Calendar.getInstance(),dateTwo=Calendar.getInstance();
//					if(Float.parseFloat(value)<=33.00f) {
//						return null;//为了忽略异常数据
//					}
					dateOne.setTime(lastSavTime);	
					//dateTwo.setTime(curTime);
					long timeOne=dateOne.getTimeInMillis();
					long timeTwo=dateTwo.getTimeInMillis();
					long minute=(timeTwo-timeOne)/(1000*60);//转化minute,得到两个时间相差的分钟数
					if(minute<5){
						return null;//间隔小于五分钟则直接跳过，不存储
					}else if(minute==5){//如果间隔时间等于五分钟
						dateOne.add(Calendar.MINUTE, 5);
						temperatureDevice.setLastSavTime(dateOne.getTime());
						temperature.setMeasureTime(dateOne.getTime());
					}else{//如果间隔大于五分钟，则进行插值
						int countToAdd=(int)minute/5;
						float distance=(degree-olddegree)/countToAdd;
						for(int i=1;i<countToAdd;i++){
							/*temperature.setMeasureNumOne((float)(Math.round((olddegree+distance*i)*100))/100);//保留两位小数
							temperature.setMeasureNumTwo(0);*/
							dateOne.add(Calendar.MINUTE, 5);
							temperature.setMeasureTime(dateOne.getTime());
							this.temperatureService.save(temperature);
							temperature.setId(null);
						}
						/*temperature.setMeasureNumOne((float)(Math.round((olddegree+distance*countToAdd)*100))/100);//保留两位小数
						temperature.setMeasureNumTwo(envTemp);*/
						dateOne.add(Calendar.MINUTE, 5);
						temperature.setMeasureTime(dateOne.getTime());
						temperatureDevice.setLastSavTime(dateOne.getTime());//更新最后数据更新时间
					}
				}
				else{
					temperature.setMeasureTime(curTime);//如果没有历史记录，则采用当前时间作为测量时间
					temperatureDevice.setLastSavTime(curTime);//更新最后数据更新时间
				}
				
			}
		}

		return temperature;
	}
	static final float YEXIA_TEMP=36.2f;//腋下温度
	static final float LEISHANG_TEMP=35.0f;//肋上温度
	private float CalibrateRealTemp(float tTemp,float envTemp,boolean ifConsiderArmsStatus){
		if (envTemp > 33.00) // 环境温度有数据，说明粘合在人体上
		{
			if(ifConsiderArmsStatus){
				if((tTemp - envTemp) > 0.6){//如果温差过大，证明已经展开了腋窝，此时视为异常，采用上一个正常值作为当前温度
					return 0;//判定是否返回0来判断是否温差异常
				}
			}
			if (tTemp > YEXIA_TEMP) // 腋下位置
			{
				/*if ((tTemp - envTemp) < 0.3) // 腋下非敞开状态下，不作任何处理，保持原始温度
					return tTemp;
				else*/ 
				if ((tTemp - envTemp) < 0.6) // 补偿上温度差，1/2的温度差
				{
					tTemp += (tTemp - envTemp) / 2.0;
					return tTemp;
				} else // 探头温度高，且手臂打开状态下
				{
					tTemp += 0.4;
				}
			} else if (tTemp > LEISHANG_TEMP) // 探头温度已经超过腋下底线温度
			{
				if ((tTemp - envTemp) < 0.2) // 温度贴片位置偏下，但温度相近
				{
					//tTemp += 0.2; // 补偿腋下和肋上的温度差
				} else if ((tTemp - envTemp) < 1)
					tTemp += (tTemp - envTemp) / 2.0; // 小幅度温度补偿
				else {
					// 防止出现粘贴在手上的处理方法
					tTemp += 1.0;
				}
			} // else if(tTemp > LEISHANG_TEMP)
			else // 体温出现特别低的情况
			{
				if((tTemp - envTemp) > 0.5){
					tTemp+=1;
				}

			}
			// 确保最终温度要高于36.3
			if (envTemp > 33.5) // 必须确保环境温度超过34才会处理
			{
				/*for (int i = 0; i < 100; i++) {
					tTemp += 0.1;
					if (tTemp > 36.2)
						break;
				}*/
			} //else
				//tTemp += 1.2;
			

		}
		if(tTemp<15){
			tTemp=15;
		}
		return tTemp;
	}

	/**
	 *  向Socket中写入回应信息
	 * 
	 * @param socket
	 * @return
	 * @throws IOException
	 */
	private BufferedOutputStream getWriter(Socket socket) throws IOException {
		OutputStream socketOut = socket.getOutputStream();
		return new BufferedOutputStream(socketOut);
	}

	/**
	 * 获取Socket的发送信息
	 * 
	 * @param socket
	 * @return
	 * @throws IOException
	 */
	private BufferedInputStream getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedInputStream(socketIn);
	}
//	boolean ifConnInfoShown=false;
	int counter400=-1;//血氧
	int counter401=-1;//心电
	int counter402=-1;//连续血压
	int counter403=-1;//呼吸
	int counter404=-1;//温度
	int counter405=-1;//血压
	
	File fileWrite = null;
	FileOutputStream fos = null;

	public boolean isOSLinux() {
		Properties prop = System.getProperties();
		String os = prop.getProperty("os.name");
		if (os != null && os.toLowerCase().indexOf("linux") > -1) {
			return true;
		} else {
			return false;
		}
	}
	
//	Jedis jedis=null;//2018年5月10日19:55:04
	@Override
	public void run() {
		try {
			logger.info("接受新连接：  " + socket.getInetAddress() + ":"
					+ socket.getPort());
			synchronized (GatherServerStatic.class) {
				GatherServerStatic.servers_count += 1;
			}
			logger.info("当前连接数量： " + GatherServerStatic.servers_count);
			socket.setSoTimeout(5000);
			BufferedInputStream br = getReader(socket);
			byte[] dest = new byte[118];byte[] temp=new byte[1];
			byte[] dataBytes = null;
			int byteNum;
			byte[] dataBytesTemp =null;//临时存放读取的数据，以防一条消息分多条发送，通过拼接方法解决此问题
			byte[] dataBytesTempRes = new byte[118];
			int flag=0;//是否已经获取了部分数据的标志，0代表没有，1代表已经有
			loop:while (true) {//!socket.isClosed()
//				socket.sendUrgentData(0xFF);
				byteNum = br.read(dest);
				if(byteNum<0){
					break;
				}
				while (byteNum<118) {
					try {
						byteNum=br.read(dest,byteNum,118-byteNum);//(33-byteNum)<0?0:(33-byteNum)
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						logger.error("startindex:"+byteNum+" length:"+(118-byteNum));
						break loop;
					}
					byteNum+=byteNum>-1?byteNum:0;
//					logger.info("长度小于118，继续收取补齐！");
				}

				while (dest[0]!=-86||dest[117]!=85) {
					//logger.info("首尾不对，继续一个个字节收取直到匹配正确为止！{}",ByteUtil.convertByteToString(dest));
					dest=ArrayUtils.subarray(dest, 1, 118);
					if (br.read(temp)<=0) {
						break loop;
						//logger.info("br.read(temp)失败"+br.available());
						
					}
					dest=ArrayUtils.addAll(dest,temp);
				}
				dataBytes=dest;
				//将原始数据保存在指定文件夹下
				mac=ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 1, 7));
				Bed bed = bedService.getPatientIdBybed(mac);
				String patientId = bed.getPatient().getId();
				if(patientId!=null && patientId!="")
				if (true)
				{
					if (fileWrite == null) {
						String path = this.getClass().getResource("").getPath();
						path = path.replaceAll("%20", " ");
						//查找“WEB-INF”在该字符串的位置
						int num = path.indexOf("WEB-INF");
						//截取字符串
						String path2 = path.substring(0, num + "WEB-INF".length() + 1);

						if (isOSLinux() == true) {
							path2 = path2 + "SorceFiles/";
						} else {
							path2 = path2 + "SorceFiles/";
						}

						//System.out.println(path2);
						String name = mac;
						SimpleDateFormat dataformat = new SimpleDateFormat("yyyy.MM.dd_HH.mm.ss");//设置日期格式
						String DataNowString = dataformat.format(new Date());// new Date()为获取当前系统时间
						//fileWrite = new File(path2 + name + "_" + patientId + "_" + DataNowString + ".bin");
						fileWrite = new File(path2 + name + "_" + DataNowString + ".bin");

						//如果文件夹不存在，则创建
						File fileParent = fileWrite.getParentFile();
						if (!fileParent.exists()) {
							fileParent.mkdirs();
						}

						fos = new FileOutputStream(fileWrite.getPath());
						fos.write(dataBytes);
					} else {
						fos.write(dataBytes);
						//fos.close();
						//System.out.println("已有文件");
					}
				}
//				String path=this.getClass().getResource("").getPath();
//				String path1=path.substring(1);
//				String path2=path.substring(1,67);
//				System.out.println(path2);
//				String name=mac;
//				File file = new File(path2+name+".txt");
//				FileWriter out = new FileWriter(file);
//				FileOutputStream fos = new FileOutputStream(path2+name+".txt");
//				//如果文件不存在，则创建新的文件
//	            if(!file.exists()){
//	                file.createNewFile();
//	                //创建文件成功后，写入内容到文件里
//	                fos.write(dataBytes);
//	        		System.out.println("唯有文件");
//	            }
//	            	fos.write(dataBytes);
//		        	fos.close();
//					System.out.println("已有文件");
	          
//				logger.info("接收到的信息:{}",ByteUtil.convertByteToString(dataBytes));
				DataResponse response = new DataResponse();
				//this.checkDataInfo(dataBytes,response);
				analyzeData(dataBytes);
				/*Temperature temperature = this.checkDataInfo(dataBytes,
						response);
				if (temperature != null) {
					this.temperatureService.save(temperature);
				}*/
			}
		
		
			
		} catch (IOException e) {
			logger.error(e.getMessage(), e.fillInStackTrace());
		} finally {
			synchronized (GatherServerStatic.class) {
				GatherServerStatic.servers_count -= 1;
			}
			logger.info("当前连接数量： " + GatherServerStatic.servers_count);
			try {
				if (scheduleMQ4Ecg!=null) {
					scheduleMQ4Ecg.interrupt();
				}
				if (scheduleMQ4Oximetry!=null) {
					scheduleMQ4Oximetry.interrupt();
				}
				if (scheduleMQ4PBP!=null) {
					scheduleMQ4PBP.interrupt();
				}
				if (scheduleMQ4RESP!=null) {
					scheduleMQ4RESP.interrupt();
				}
				if (socket != null)
					socket.close();
//				RedisManager.close(jedis);//2018年5月10日19:54:44
			} catch (IOException e) {
				e.printStackTrace();
			}      
		}
	}
	public boolean isConnected(Socket s){
        try{
            s.sendUrgentData(0xFF);
            return true;
        }catch(Exception e){
            return false;
        }
	}
	private void analyzeData(byte[] dataBytes) {
		try{
			
			if ("".equals(mac)) {
				macBytes=ArrayUtils.subarray(dataBytes, 1, 7);
				mac=ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 1, 7));
				logger.info("连接信息：  " + socket.getInetAddress() + ":"
						+ socket.getPort()+"|"+mac);
			}
			//将mac地址保存在redis
			RedisManager.set("mac", String.valueOf(mac));
			//绑定床位
			/*if(DeviceSettings.lstMacs4Concentrator.contains(mac)){
			logger.error("该集中器未绑定床位！");
		}*/
			
			String flag=ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 7, 8));
			int count=0;
			switch (flag) {
			case "00"://血氧数据
				//初始化消息队列数据消息消费线程
				if (scheduleMQ4Oximetry==null) {
					scheduleMQ4Oximetry=new ScheduleMQ4Oximetry(ArrayUtils.subarray(dataBytes, 1, 8));
					scheduleMQ4Oximetry.start();
				}
				//丢包统计相关
				count=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 116, 117)),16);
				if (-1==counter400) {
//					counter400=count;
				}else if (count != (counter400 + 1) % 256){
					logger.info("DataLostStastics--mac:{},type:00SPO2,countNo:{},lastCout:{},lostCout:{}", mac,count,counter400,count>counter400?count-counter400-1:count+255-counter400);
				}
				counter400=count;
				analysisOximetry(dataBytes);
				
				break;
			case "01"://心电数据
				//logger.info("ECG:{}",ByteUtil.convertByteToString(dataBytes));
				//初始化消息队列数据消息消费线程
				if (scheduleMQ4Ecg==null) {
					scheduleMQ4Ecg=new ScheduleMQ4Ecg(ArrayUtils.subarray(dataBytes, 1, 8));
					scheduleMQ4Ecg.start();
				}
				//丢包统计相关
				count=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 116, 117)),16);
				if (-1==counter401) {
//					counter401=count;
				}else if (count != (counter401 + 1) % 256){
					logger.info("DataLostStastics--mac:{},type:01ECG,countNo:{},lastCout:{},lostCout:{}", mac,count,counter401,count>counter401?count-counter401-1:count+255-counter401);
				}
				counter401=count;
				analysisEcg(dataBytes);
				break;
			case "02"://连续血压数据
				//初始化消息队列数据消息消费线程
				if (scheduleMQ4PBP==null) {
					scheduleMQ4PBP=new ScheduleMQ4PBP(ArrayUtils.subarray(dataBytes, 1, 8));
					scheduleMQ4PBP.start();
				}
				//丢包统计相关
				count=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 116, 117)),16);
				if (-1==counter402) {
//					counter402=count;
				}else if (count != (counter402 + 1) % 256){
					logger.info("DataLostStastics--mac:{},type:02PWV,countNo:{},lastCout:{},lostCout:{}", mac,count,counter402,count>counter402?count-counter402-1:count+255-counter402);
				}
				counter402=count;
				analysisPBP(dataBytes);
				break;
			case "03"://呼吸数据
				//初始化消息队列数据消息消费线程
				if (scheduleMQ4RESP==null) {
					scheduleMQ4RESP=new ScheduleMQ4RESP(ArrayUtils.subarray(dataBytes, 1, 8));
					scheduleMQ4RESP.start();
				}
				//丢包统计相关
				count=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 116, 117)),16);
				if (-1==counter403) {
//					counter403=count;
				}else if (count != (counter403 + 1) % 256){
					logger.info("DataLostStastics--mac:{},type:03RESP,countNo:{},lastCout:{},lostCout:{}", mac,count,counter403,count>counter403?count-counter403-1:count+255-counter403);
				}
				counter403=count;
				analysisRESP(dataBytes);
				break;
			case "04"://温度数据
//				logger.info("Tep:{}",ByteUtil.convertByteToString(dataBytes));
				//丢包统计相关
				count=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 116, 117)),16);
				if (-1==counter404) {
//					counter404=count;
				}else if (count != (counter404 + 1) % 256){
					logger.info("DataLostStastics--mac:{},type:04TEMP,countNo:{},lastCout:{},lostCout:{}", mac,count,counter404,count>counter404?count-counter404-1:count+255-counter404);
				}
				counter404=count;
				analysisTemperature(dataBytes);
				break;
			/*case "05"://温度数据2
				analysisTemperature(dataBytes);
				break;*/
			case "05"://无创血压数据
				//丢包统计相关
				count=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 116, 117)),16);
				if (-1==counter405) {
//					counter405=count;
				}else if (count != (counter405 + 1) % 256){
					logger.info("DataLostStastics--mac:{},type:05NIBP,countNo:{},lastCout:{},lostCout:{}", mac,count,counter405,count>counter405?count-counter405-1:count+255-counter405);
				}
				counter405=count;
				analysisBloodPressure(dataBytes);
				break;
			default:
				break;
			}	
		}catch(Exception e){
			logger.error(e.getMessage(),e.fillInStackTrace());
		}
	}
	private void analysisOximetry(byte[] dataBytes){
		//RedisManager.lpush(macBytes, dataBytes);//"/oxi/"+mac
		//mac+flag
		//2018年5月10日19:50:29 改为不用每次重新获取redis连接，一个线程用一个redis连接
		//RedisManager.lpush(jedis,ArrayUtils.subarray(dataBytes, 1, 8), dataBytes);
		RedisManager.lpush(ArrayUtils.subarray(dataBytes, 1, 8), dataBytes);
	}
	private void analysisEcg(byte[] dataBytes){
		RedisManager.lpush(ArrayUtils.subarray(dataBytes, 1, 8), dataBytes);
	}
	private void analysisPBP(byte[] dataBytes){
		RedisManager.lpush(ArrayUtils.subarray(dataBytes, 1, 8), dataBytes);
	}
	private void analysisBloodPressure(byte[] dataBytes){
		if (bloodPressureDevice==null) {
			bloodPressureDevice=new BloodPressureDevice();
			bloodPressureDevice.setStrMac(mac);
		}
		BloodPressure bloodPressure=new BloodPressure();
		bloodPressure.setConcentratorNo(mac);
		Date curTime=new Date();
		ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 8, 9));
		//获取血压和脉搏(心率)数据
		int strHighPressure=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 8, 10)),16);
		int strLowPressure=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 10, 12)),16);
		int strPulserate=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 12, 13)),16);
		int count=Integer.parseInt(ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 12, 13)),16);
		if (65535==strHighPressure) {
			strHighPressure=-1;
			strLowPressure=-1;
		}
		bloodPressure.setHighPressure(strHighPressure);
		bloodPressure.setLowPressure(strLowPressure);
		bloodPressure.setPulserate(strPulserate);
		bloodPressure.setCount(count);
		
		//历史数据回顾存入redis
		RedisManager.set("Sbp", String.valueOf(strHighPressure));
		RedisManager.set("Dbp", String.valueOf(strLowPressure));
		RedisManager.set("BP4PR", String.valueOf(strPulserate));
		
		//获取mac地址对应的床位，更新其温度值
		/*for (Bed bed : DeviceSettings.lstBeds) {
			if (!bed.getStatus().equals(PublicSetting.BED_STATUS_EMPTY)&&bed.getConcentratorNo().equals(mac)) {
				bed.setBloodPressure(bloodPressure);
				break;
			}
		}*/
		Bed bed=DeviceSettings.hasBeds.get(mac);
		if (bed!=null&&!bed.getStatus().equals(PublicSetting.BED_STATUS_EMPTY)) {
			if (null!=bed.getBloodPressure()) {
				if (bed.getBloodPressure().getCount()==count) {
					bloodPressure.setLastUpdateTime(bed.getBloodPressure().getLastUpdateTime());
				}else{
					bloodPressure.setLastUpdateTime(curTime);
				}
			}else{
				bloodPressure.setLastUpdateTime(curTime);
			}
			bed.setBloodPressure(bloodPressure);
			bed.setBloUpdateMs(System.currentTimeMillis());
		}
		Date lastSavTime;
		dateTwo.setTime(curTime);
		lastSavTime=bloodPressureDevice.getLastSavTime();//最后数据上传时间
		if(lastSavTime!=null){//如果不为空则判断是否要存，为空则直接存储，不作其他处理
			dateOne.setTime(lastSavTime);	
			//dateTwo.setTime(curTime);
			long timeOne=dateOne.getTimeInMillis();
			long timeTwo=dateTwo.getTimeInMillis();
			long minute=(timeTwo-timeOne)/(1000*60);//转化minute,得到两个时间相差的分钟数
			if(minute<5){
				return ;//间隔小于五分钟则直接跳过，不存储
			}else if(minute==5){//如果间隔时间等于五分钟
				dateOne.add(Calendar.MINUTE, 5);
				temperatureDevice.setLastSavTime(dateOne.getTime());
				bloodPressure.setMeasureTime(dateOne.getTime());
			}else{//如果间隔大于五分钟，则进行插值
				int countToAdd=(int)minute/5;
				for(int i=1;i<countToAdd;i++){
					dateOne.add(Calendar.MINUTE, 5);
					bloodPressure.setMeasureTime(dateOne.getTime());
					this.bloodPressureService.save(bloodPressure);
					bloodPressure.setId(null);
				}
				dateOne.add(Calendar.MINUTE, 5);
				bloodPressure.setMeasureTime(dateOne.getTime());
				bloodPressureDevice.setLastSavTime(dateOne.getTime());//更新最后数据更新时间
			}
		}
		else{
			bloodPressure.setMeasureTime(curTime);//如果没有历史记录，则采用当前时间作为测量时间
			bloodPressureDevice.setLastSavTime(curTime);//更新最后数据更新时间
		}
		this.bloodPressureService.save(bloodPressure);
	}                     
	private void analysisRESP(byte[] dataBytes){
		RedisManager.lpush(ArrayUtils.subarray(dataBytes, 1, 8), dataBytes);
	}
	private void analysisTemperature(byte[] dataBytes){
		if (temperatureDevice==null) {
			temperatureDevice=new TemperatureDevice();
			temperatureDevice.setStrMac(mac);
		}
		Temperature temperature = new Temperature();
		temperature.setConcentratorNo(mac);
		Date curTime=new Date();
		// 获取温度1信息
		String temp = ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 8, 9))+ "."+ ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 9, 10));
		float degree=Float.parseFloat(temp.substring(0, temp.length()-1));
		float MeasureNum=(float)(Math.round((degree)*100))/100;
		temperature.setMeasureNum(MeasureNum);
		String temp2 = ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 10, 11))+ "."+ ByteUtil.convertByteToString(ArrayUtils.subarray(dataBytes, 11, 12));
		float degree2=Float.parseFloat(temp2.substring(0, temp.length()-1));
		float MeasureNum2=(float)(Math.round((degree2)*100))/100;
		temperature.setMeasureNum2(MeasureNum2);
		//将解析温度存入-redis
		
		RedisManager.set("Temperature1", String.valueOf(MeasureNum));
		RedisManager.set("Temperature2", String.valueOf(MeasureNum2));
	
		//获取mac地址对应的床位，更新其温度值
		/*for (Bed bed : DeviceSettings.lstBeds) {
			if (!bed.getStatus().equals(PublicSetting.BED_STATUS_EMPTY)&&bed.getConcentratorNo().equals(mac)) {
				bed.setTemperature(temperature);
				break;
			}
		}*/
		Bed bed=DeviceSettings.hasBeds.get(mac);
		if (bed!=null&&!bed.getStatus().equals(PublicSetting.BED_STATUS_EMPTY)) {
			bed.setTemperature(temperature);
			bed.setTemUpdateMs(System.currentTimeMillis());
		}
		float olddegree=0;
		//degree=CalibrateRealTemp(degree,envTemp,true);
		//判断是否五分钟内存储过了数据，如果没有则存储，并根据时差做两个温度的差值补上没有的数据
		Date lastSavTime;
		dateTwo.setTime(curTime);
		//判断是否为历史数据,如果是历史数据则将计算出的历史时间作为curTime
		/*if(!(ByteUtil.convertByteToString(dataBytes[21])+ByteUtil.convertByteToString(dataBytes[20])).equals("0000")){
			try {
				dateTwo.setTime(temperatureDevice.getFirstSavTime());
				dateTwo.add(Calendar.MINUTE, Integer.parseInt(ByteUtil.convertByteToString(dataBytes[21])+ByteUtil.convertByteToString(dataBytes[20]),16));
				//如果添加病人以及某个贴片后，中间服务器重启了，会造成上边计算出的历史时间后于现在时间，此情况则忽略历史数据
				if(curTime.getTime()<=dateTwo.getTime().getTime())
					return;
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return ;
			}
			
		}*/
		lastSavTime=temperatureDevice.getLastSavTime();//最后数据上传时间
		if(lastSavTime!=null){//如果不为空则判断是否要存，为空则直接存储，不作其他处理
			dateOne.setTime(lastSavTime);	
			//dateTwo.setTime(curTime);
			long timeOne=dateOne.getTimeInMillis();
			long timeTwo=dateTwo.getTimeInMillis();
			long minute=(timeTwo-timeOne)/(1000*60);//转化minute,得到两个时间相差的分钟数
			if(minute<5){
				return ;//间隔小于五分钟则直接跳过，不存储
			}else if(minute==5){//如果间隔时间等于五分钟
				dateOne.add(Calendar.MINUTE, 5);
				temperatureDevice.setLastSavTime(dateOne.getTime());
				temperature.setMeasureTime(dateOne.getTime());
			}else{//如果间隔大于五分钟，则进行插值
				int countToAdd=(int)minute/5;
				float distance=(degree-olddegree)/countToAdd;
				for(int i=1;i<countToAdd;i++){
					dateOne.add(Calendar.MINUTE, 5);
					temperature.setMeasureTime(dateOne.getTime());
					this.temperatureService.save(temperature);
					temperature.setId(null);
				}
				dateOne.add(Calendar.MINUTE, 5);
				temperature.setMeasureTime(dateOne.getTime());
				temperatureDevice.setLastSavTime(dateOne.getTime());//更新最后数据更新时间
			}
		}
		else{
			temperature.setMeasureTime(curTime);//如果没有历史记录，则采用当前时间作为测量时间
			temperatureDevice.setLastSavTime(curTime);//更新最后数据更新时间
		}
		this.temperatureService.save(temperature);
	}
	

	
}